package com.example.coursehub.service.impl;

import com.example.coursehub.dto.Identity;
import com.example.coursehub.dto.UserUpdateDto;
import com.example.coursehub.entity.Course;
import com.example.coursehub.entity.User;
import com.example.coursehub.repository.CourseRepository;
import com.example.coursehub.repository.CourseStudentRepository;
import com.example.coursehub.repository.CourseTeacherRepository;
import com.example.coursehub.repository.UserRepository;
import com.example.coursehub.service.UserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final CourseRepository courseRepository;
    private final CourseTeacherRepository courseTeacherRepository;
    private final CourseStudentRepository courseStudentRepository;
    private final PasswordEncoder passwordEncoder;

    public UserServiceImpl(UserRepository userRepository, CourseRepository courseRepository, CourseTeacherRepository courseTeacherRepository, CourseStudentRepository courseStudentRepository,PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.courseRepository = courseRepository;
        this.courseTeacherRepository = courseTeacherRepository;
        this.courseStudentRepository = courseStudentRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public User registerUser(User user) {
        System.out.println("收到注册请求" + user + "@@" + user.getUserAccount() + "@@" + user.getUserName() + "@@" + user.getUserPassword());
        if (user.getUserAccount() == null || user.getUserAccount().trim().isEmpty()) {
            System.out.println("账号不能为空");
            return null;
        }
        user.setUserId("U"+user.getUserAccount());
        if (userRepository.existsById(user.getUserId())) {
            System.out.println("用户已存在");
            return null;
        }
        String rawPassword = user.getUserPassword();
        String encodedPassword = passwordEncoder.encode(rawPassword);
        user.setUserPassword(encodedPassword);
        return userRepository.save(user);
    }

    @Override
    public User updateUser(String userId, User user, String password) {
        Optional<User> existingUserOpt = userRepository.findById(userId);
        System.out.println("收到更新请求" + user + "@@" + user.getUserAccount() + "@@" + user.getUserName() + "@@" + user.getUserPassword());
        if (existingUserOpt.isPresent()) {
            User existingUser = existingUserOpt.get();
            existingUser.setUserName(user.getUserName());
            existingUser.setUserAccount(user.getUserAccount());

            if (!existingUser.getUserPassword().equals(user.getUserPassword())) {
                existingUser.setUserPassword(user.getUserPassword()); // 使用明文密码
            }

            return userRepository.save(existingUser);
        }
        return null; // 用户不存在
    }

    @Override
    public void deleteUser(String userId) {
        userRepository.deleteById(userId);
    }

    @Override
    public User getUserById(String userId) {
        return userRepository.findById(userId).orElse(null); // 如果找不到用户，返回null
    }

    @Override
    public boolean checkUserPassword(String userid, String password) {
        User user1 = userRepository.findById(userid).orElse(null);
        return user1 != null && passwordEncoder.matches(password, user1.getUserPassword());
    }


    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll(); // 返回所有用户列表
    }

    @Override
    public User login(String account, String password) {
        Optional<User> userOpt = userRepository.findByUserAccount(account); // ✅ 改为通过 user_account 查询
        if (userOpt.isPresent() ) {
            User user =  userOpt.get();
            if(passwordEncoder.matches(password, user.getUserPassword())){
                return user;
            }
        }
        return null;
    }


    @Override
    public void logout() {
        // 模拟登出：无需具体实现
    }

    @Override
    @Transactional
    public User updateUserInfo(String userId, UserUpdateDto updateDto) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // ✅ 使用 passwordEncoder 校验密码
        if (!passwordEncoder.matches(updateDto.getCurrentPassword(), user.getUserPassword())) {
            throw new IllegalArgumentException("当前密码不正确");
        }

        // 更新用户名
        if (updateDto.getNewName() != null && !updateDto.getNewName().isBlank()) {
            user.setUserName(updateDto.getNewName());
        }

        // 更新密码（需要加密）
        if (updateDto.getNewPassword() != null && !updateDto.getNewPassword().isBlank()) {
            user.setUserPassword(passwordEncoder.encode(updateDto.getNewPassword()));
        }

        return userRepository.save(user);
    }


    @Override
    public String getUserRoleInCourse(String courseId, String userId) {
        Map<String, Object> result = new HashMap<>();

        // 验证课程和用户是否存在
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new IllegalArgumentException("课程不存在"));

        User user = userRepository.findById(userId)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));

        // 检查是否为教师
        boolean isTeacher = courseTeacherRepository.existsById_courseIdAndId_userId(courseId, userId);

        // 检查是否为学生
        boolean isStudent = courseStudentRepository.existsById_courseIdAndId_userId(courseId, userId);

        // 确定角色
        Identity role;
        if (isTeacher) {
            role = Identity.TEACHER;
        } else if (isStudent) {
            role = Identity.STUDENT;
        } else {
            role = Identity.UNKNOWN;
        }

        return role.toString();
    }
}
